package controller

import (
	"fmt"
	"hytx_manager/middleware/auth"
	"hytx_manager/models"
	"github.com/gin-gonic/gin"
	"hytx_manager/pkg/app"
	"net/http"
)

func Test(c *gin.Context) {
	appG := app.Gin{C: c}
	//m := AppCateArr(0)

	var data []*models.Permission
	_ = models.DB.Table("permissions").Find(&data).Error

	list := buildData(data)
	m := makeTreeCore(0, list)

	appG.ResponseMsg(http.StatusOK, "ok", m)
	fmt.Println(auth.User(c))
}

type AppCateNode struct {
	Id int `json:"id"`
	Name string `json:"name"`
	Sub []*AppCateNode `json:"sub"`
}

func AppCateArr(pid int) []*AppCateNode {
	var data []*models.Permission
	_ = models.DB.Table("permissions").Where("parent_id=?", pid).Find(&data).Error
	if data == nil {
		return nil
	}

	apc_node := []*AppCateNode{}
	for _, v := range data {
		chd := AppCateArr(v.ID)
		node := &AppCateNode{
			Id:   v.ID,
			Name: v.Name,
		}
		node.Sub = chd
		apc_node = append(apc_node, node)
	}
	return apc_node
}

func buildData(list []*models.Permission) map[int]map[int]*models.Permission {
	data := make(map[int]map[int]*models.Permission)
	for _, v := range list {
		id := v.ID
		fid := v.ParentId
		if _, ok := data[fid]; !ok {
			data[fid] = make(map[int]*models.Permission)
		}
		data[fid][id] = v
	}
	return data
}

func makeTreeCore(index int, data map[int]map[int]*models.Permission) []*models.Permission {
	tmp := make([]*models.Permission, 0)
	for id, item := range data[index] {
		if data[id] != nil{
			item.Sub = makeTreeCore(id, data)
		}
		tmp = append(tmp, item)
	}
	return tmp
}


func AuthTest(c *gin.Context) {
	user := auth.User(c)
	render(c, user)
}